﻿using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Security.Claims;
using System.Threading.Tasks;
using AutoMapper;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Oliving.Edge.AOP;
using Oliving.Edge.AuthHelper;
using Oliving.Edge.Common;
using Oliving.Edge.Common.LogHelper.Nlog;
using Oliving.Edge.Dto.Oliving;
using Oliving.Edge.IServices.Oliving;
using Oliving.Edge.Model;
using Oliving.Edge.Model.Models;
using Oliving.Edge.Model.ViewModels.Oliving;
using Oliving.Edge.SwaggerHelper;
using static Oliving.Edge.SwaggerHelper.CustomApiVersion;

namespace Oliving.Edge.Controllers.Oliving
{
    [Route("api/SysConfig_")]
    [ApiController]
    //[Authorize]
    //[Authorize(Roles = "Admin,Client")]
    //[Authorize(Policy = "SystemOrAdmin")]
    //[Authorize(PermissionNames.Permission)]
    [Authorize(Permissions.Name)]
    public class SysConfig_Controller : OlivingControll
    {

        #region 构造函数

        private readonly ISys_configServices _sys_configServices;

        private readonly ILogger<SysConfig_Controller> _logger;
        IMapper _mapper;

        public SysConfig_Controller(
            IHttpContextAccessor accessor, PermissionRequirement requirement,

            ISys_configServices sys_configServices,
            ILogger<SysConfig_Controller> logger,
            IMapper mapper

            ) : base(accessor, requirement)
        {
            _sys_configServices = sys_configServices;
            _logger = logger;
            _mapper = mapper;
        }

        #endregion

        #region Vue

        /// <summary>
        /// 获取详情
        /// </summary>
        /// <returns></returns>
        //[HttpGet("{id}")] // 参数不可为空
        [HttpGet] // 参数不可为空
        [AllowAnonymous]
        [Route("/api/[controller]/Get")]
        public async Task<MessageModel<Sys_configDto>> Get(int id)
        {

            var data = new MessageModel<Sys_configDto>();

            // 测试 AOP 缓存
            Sys_configDto dto = await _sys_configServices.GetDto(id);
            data.response = dto;
            data.msg = "获取成功！";
            data.success = true;
            return data;
        }



        [HttpGet]
        [Route("/api/[controller]/GetPageList")]
        public async Task<MessageModel<PageModel<Sys_configDto>>> GetPageList(int page = 1, int intPageSize = 20, string key = "")
        {


            if (string.IsNullOrEmpty(key) || string.IsNullOrWhiteSpace(key))
            {
                key = "";
            }

            var data = await _sys_configServices.QueryPage(a =>
                         a.C_State > -1
                         && ((a.C_Name != null && a.C_Name.Contains(key))
                             || (a.C_Key != null && a.C_Key.Contains(key)))
                         , page, intPageSize, " C_ID desc ");

            var model = _mapper.Map<PageModel<Sys_configDto>>(data);

            return new MessageModel<PageModel<Sys_configDto>>()
            {
                msg = "获取成功",
                success = data.dataCount >= 0,
                response = model
            };
        }


        #endregion

        #region MyRegion

        [HttpPut]
        [Route("/api/[controller]/Update")]
        //public async Task<MessageModel<string>> Put([FromBody] Sys_configDto dto)
        public async Task<MessageModel<string>> Update([FromBody] Sys_configDto dto)
        {
            var data = new MessageModel<string>();

            if (dto != null && dto.C_ID > 0)
            {
                //var model = _mapper.Map<PageModel<sys_config>>(dto);

                sys_config model = await _sys_configServices.QueryById(dto.C_ID);

                model.C_Key = dto.C_Key;
                model.C_Name = dto.C_Name;
                model.C_Value = dto.C_Value;
                model.C_Renark = dto.C_Renark;

                data.success = await _sys_configServices.Update(model);

                if (data.success)
                {
                    data.msg = "更新成功";
                    data.response = dto.C_ID.ObjToString();
                }
            }
            return data;
        }


        [HttpPost]
        [Route("/api/[controller]/Add")]
        public async Task<MessageModel<string>> Add(sys_config dto)
        {
            var data = new MessageModel<string>();
            int id = await _sys_configServices.Add(dto);

            data.success = id > 0;
            if (data.success)
            {
                data.response = id.ObjToString();
                data.msg = "添加成功";
            }
            return data;
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        // DELETE: api/ApiWithActions/5
        [HttpDelete]
        [Route("/api/[controller]/Delete")]
        public async Task<MessageModel<string>> Delete(int id)
        {
            var data = new MessageModel<string>();
            if (id > 0)
            {
                var userDetail = await _sys_configServices.QueryById(id);
                userDetail.C_State = -1;
                data.success = await _sys_configServices.Update(userDetail);
                if (data.success)
                {
                    data.msg = "删除成功";
                    data.response = userDetail?.C_ID.ObjToString();
                }
            }

            return data;
        }


        /// <summary>
        /// 测试批量删除，如果是axios，记得要把数组格式化成 stringQuery
        /// </summary>
        /// <param name="ids"></param>
        /// <returns></returns>
        [HttpDelete]
        [Route("/api/[controller]/BatchDelete")]
        public async Task<MessageModel<string>> BatchDelete(string ids)
        {
            var data = new MessageModel<string>();
            if (!string.IsNullOrEmpty(ids))
            {
                if (false)
                {
                    #region 软删除

                    int[] list = Array.ConvertAll<string, int>(ids.Split(','), s => int.Parse(s));

                    var mlist = _sys_configServices.Query(t => list.Contains(t.C_ID));

                    var userDetail = _sys_configServices.Update(mlist);
                    sys_config model = new sys_config();
                    model.C_State = -1;
                    string whereStr = " C_ID in (" + ids + ")";
                    List<string> colList = new List<string>();
                    colList.Add("C_State");
                    List<string> colHL = new List<string>();
                    // await
                    bool isOK = await _sys_configServices.Update(model, colList, colHL, whereStr);


                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }

                    #endregion
                }

                {
                    #region 直接删除 

                    object[] list = Array.ConvertAll<string, object>(ids.Split(','), s => int.Parse(s));

                    bool isOK = await _sys_configServices.DeleteByIds(list);

                    data.success = isOK;
                    if (data.success)
                    {
                        data.msg = "删除成功";
                        data.response = list.Count().ObjToString();
                    }

                    #endregion
                }

            }

            return data;


        }


        #endregion

    }


}